<?php

require_once 'model/block.class.php';

class Core_Table_Block extends Database_Table
{
	protected $_name = 'appearance_block';

	protected $_rowClass = 'Core_Table_Model_Block';

	function loadForRender($layoutId)
	{
		/**
		 * @var array
		 */
		$return = array();

		/**
		 * load section spec
		 */
		$layout = Nuo::getTable('core/layout') -> find($layoutId) -> current();

		if (!$layout)
		{
			return $layout;
		}

		$return['section'] = $layout -> toArray();

		$sql = <<<SQL
SELECT widget.*, block.* FROM :widget AS widget 
JOIN :block AS block ON(widget.widget_id = block.widget_id)
WHERE block.layout_id = :layout_id AND block.is_enabled=1 and widget.is_enabled=1
ORDER BY sort_order
SQL;
		$sql = strtr($sql, array(
			':widget' => Nuo::getTable('core/widget') -> getName(),
			':block' => Nuo::getTable('core/block') -> getName(),
			':layout_id' => $layoutId,
		));
		

		$temp_items = $this -> getAdapter() -> fetchAll($sql);

		// final list of items.
		$items = array();

		// map parent_element_id => parent_id
		foreach ($temp_items as $item)
		{
			$items[$item['block_id']] = $item;
		}

		unset($temp_items);

		for ($i = 0; $i < 10; ++$i)
		{

			// define some thing else.
			$map_p2c = array();
			$found = false;

			// map parent_element_id => parent_id
			foreach ($items as $item)
			{
				$map_p2c[$item['parent_id']] = 1;
			}

			foreach ($items as $key => $item)
			{
				$id = $item['block_id'];
				$pid = $item['parent_id'];

				// process p1.
				if (0 == $pid)
				{
					continue;
				}

				if (!isset($map_p2c[$id]) && $map_p2c[$pid] == 1)
				{
					$found = true;
					if (isset($items[$pid]) && is_array($items[$pid]))
					{
						$items[$pid]['items'][] = $item;
					}
					unset($items[$key]);
				}
				else
				{
					// temporary block parent node.
					$map_p2c[$pid] = 2;
				}
			}
			if (!$found)
			{
				break;
			}
		}

		$regions = array();

		foreach ($items as $key => $item)
		{
			if ($item['parent_id'] != 0)
			{
				unset($items[$key]);
			}
			else
			{
				$regions[$item['region_id']][] = $item;
			}
		}

		unset($items);
		$return['regions'] = $regions;
		
		return $return;
	}

}
